const http = require("http");
const path = require("path");
const fs = require("fs");

// 创建一个HTTP服务器
const server = http.createServer();

// 监听客户端的请求事件
server.on("request", (req, res) => {
  // 设置响应头，指定内容类型为HTML，编码为UTF-8
  //res.setHeader("Content-Type", "text/html; charset=utf-8");
  var url = req.url;
  let fpath;
  if (url === "/") {
    fpath = path.join(__dirname, "/clock", "/index.html");
  } else {
    fpath = path.join(__dirname, "/clock", url);
  }

  fs.readFile(fpath, "utf-8", (err, data) => {
    if (err) {
      res.statusCode = 404;
      res.end("<h1>404 Not Found</h1>");
    } else {
      res.end(data);
    }
  });
});

// 启动服务器，监听指定端口
const PORT = 3000;
const HOST = "127.0.0.1";
server.listen(PORT, HOST, () => {
  console.log(`服务器已启动，正在监听端口 ${PORT}...`);
  console.log(`http://${HOST}:${PORT}`);
});
